package com.example.shop.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.shop.mapper.LogsMapper;
import com.example.shop.pojo.Logs;
import com.example.shop.pojo.UserAuth;
import com.example.shop.service.UserAuthService;
import com.example.shop.utils.AutoLogout;
import com.example.shop.utils.LogsLevel;
import com.example.shop.utils.LogsRecord;
import com.example.shop.utils.Result;
import com.example.shop.utils.UserIdSession;

/**
 * 日志模块接口
 * 
 * @author Administrator
 *
 */
@RestController
@RequestMapping("/logs")
public class LogsController {
	@Autowired
	private LogsMapper logsMapper;
	@Autowired
	private LogsRecord logsRecord;
	@Autowired
	private UserAuthService userAuthService;
	// 文件路径
	private static final String FILE_PATH_LOGIN = "E:\\Eclipse\\file_path\\login";
	private static final String FILE_PATH_SELECT = "E:\\Eclipse\\file_path\\select";
	private static final String FILE_PATH_DELETE = "E:\\Eclipse\\file_path\\delete";
	private static final String FILE_PATH_OPERATION = "E:\\Eclipse\\file_path\\operation";
	// 日志对象
	private final static Logger logger = LoggerFactory.getLogger(LogsController.class);

//	/**
//	 * 操作日志
//	 */
//	@PutMapping("/operation")
//	public Result<String> operationLogs(@RequestBody Logs logs) {
//		// 登录校验
//		Object employee = UserIdSession.getAttribute(logs.getAccount());
//		if (employee == null) {
//			return Result.fail("NOTLOGIN");
//		}
//
//		AutoLogout.userPerformedOperation(logs.getAccount());
//
//		// 记录日志
//		String msg = logs.getAccount() + "用户操作日志";
//		logger.debug(msg);
//		logsRecord.addLogs(new Logs(null, LocalDateTime.now().toString(), LogsLevel.LOG_LEVEL_DEBUG, msg));
//
//		logsMapper.updateLogs(logs);
//		return Result.success("修改成功");
//	}
//
//	/**
//	 * 查询日志
//	 */
//	@GetMapping("/select")
//	public Result<String> selectLogs(String account) {
//		// 登录校验
//		Object employee = UserIdSession.getAttribute(account);
//		if (employee == null) {
//			return Result.fail("NOTLOGIN");
//		}
//
//		AutoLogout.userPerformedOperation(account);
//
//		// 记录日志
//		String msg = account + "用户查询日志";
//		logger.debug(msg);
//		logsRecord.addLogs(new Logs(null, LocalDateTime.now().toString(), LogsLevel.LOG_LEVEL_DEBUG, msg));
//
//		List<Logs> logs = logsMapper.selectLogs();
//		StringBuffer result = new StringBuffer();
//		for (Logs log : logs) {
//			result.append(log.toString() + "\n");
//		}
//		return Result.success(result);
//	}

	/**
	 * 删除日志
	 */
	@DeleteMapping("/drop")
	public Result<String> dropLogs(@RequestBody Logs logs) {
		// 登录校验
		Object employee = UserIdSession.getAttribute(logs.getAccount());
		if (employee == null) {
			return Result.fail("NOTLOGIN");
		}

		AutoLogout.userPerformedOperation(logs.getAccount());

		// 记录日志
		String msg = logs.getAccount() + "用户删除日志";
		logger.debug(msg);
		logsRecord.addLogs(new Logs(null, LocalDateTime.now().toString(), LogsLevel.LOG_LEVEL_DELETE, msg));

		logsMapper.removeLogs(logs.getId());
		return Result.success("删除成功");
	}

	/**
	 * 日志导出文件
	 * 
	 * @throws IOException
	 */
	@GetMapping("/export/file")
	public Result<String> exportFile(@RequestBody Logs logs) throws IOException {
		// 登录校验
		Object employee = UserIdSession.getAttribute(logs.getAccount());
		if (employee == null) {
			return Result.fail("NOTLOGIN");
		}

		// 记录用户操作
		AutoLogout.userPerformedOperation(logs.getAccount());

		// 记录日志
		String msg = logs.getAccount() + "用户导出日志";
		logger.debug(msg);
		logsRecord.addLogs(new Logs(null, LocalDateTime.now().toString(), LogsLevel.LOG_LEVEL_EXPORT_FILE, msg));

		// 读取文件
		String FILE_PATH = getPathByLogLevel(logs);
		File file = new File(FILE_PATH);
		File fileName = new File(FILE_PATH + "//logs.txt");
		if (file.isFile()) {
			return Result.fail("该文件不合法");
		}
		if (!file.exists()) {
			// 创建文件夹
			file.mkdir();
			fileName.createNewFile();
		}
		FileWriter writer = new FileWriter(fileName);
		// 查询数据库
		List<Logs> logsList = logsMapper.selectLogs(logs);
		// 导出数据到文件
		for (Logs log : logsList) {
			writer.write(log.toString());
			writer.write("\n");
		}
		// 关闭资源
		writer.close();
		return Result.success("");
	}

	/**
	 * 日志文件查询
	 * 
	 * @throws IOException
	 */
	@GetMapping("/query/file")
	public Result<String> queryFile(@RequestBody Logs logs) throws IOException {
		// 登录校验
		Object employee = UserIdSession.getAttribute(logs.getAccount());
		if (employee == null) {
			return Result.fail("NOTLOGIN");
		}

		// 记录用户操作
		AutoLogout.userPerformedOperation(logs.getAccount());

		// 权限校验
		if ("LOGIN".equals(logs.getLogLevel())) {
			List<UserAuth> userAuthLists = new ArrayList<UserAuth>();
			userAuthLists.add(new UserAuth(logs.getAccount(), 21L, 0L));
			String userAuthResult = userAuthService.checkAuth(userAuthLists);
			if (!"权限验证通过".equals(userAuthResult)) {
				return Result.fail(userAuthResult);
			}
			;
		}

		// 记录日志
		String msg = logs.getAccount() + "用户导出日志";
		logger.debug(msg);
		logsRecord.addLogs(new Logs(null, LocalDateTime.now().toString(), LogsLevel.LOG_LEVEL_QUERY_FILE, msg));

		// 读取文件
		String FILE_PATH = getPathByLogLevel(logs);
		File filename = new File(FILE_PATH + "//logs.txt");
		FileReader fr = new FileReader(filename);
		int len = -1;
		char[] buffer = new char[1024];
		StringBuffer sb = new StringBuffer();
		while ((len = fr.read(buffer)) != -1) {
			// System.out.print((char) len);
			sb.append(buffer);
		}

		return Result.success(sb);
	}
	
	
	/**
	 * 根据log_level获取文件存储路径
	 */
	public String getPathByLogLevel(Logs logs) {
		String FILE_PATH = "";
		switch (logs.getLogLevel()) {
		case LogsLevel.LOG_LEVEL_LOGIN:
			FILE_PATH = FILE_PATH_LOGIN;
			break;
		case LogsLevel.LOG_LEVEL_OPERATION:
			FILE_PATH = FILE_PATH_OPERATION;
			break;
		case LogsLevel.LOG_LEVEL_SELECT:
			FILE_PATH = FILE_PATH_SELECT;
			break;
		case LogsLevel.LOG_LEVEL_DELETE:
			FILE_PATH = FILE_PATH_DELETE;
			break;
		}
		return FILE_PATH;
	}

}
